<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="statusCode === 1">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-if="statusCode === 2">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ articleInfo.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="articleInfo.aut_photo"
          />
          <div slot="title" class="user-name">{{ articleInfo.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ articleInfo.pubdate | realtiveTime }}
          </div>
          <!-- 关注功能组件 -->
          <FollowUser
            :authorId="articleInfo.aut_id"
            v-model="articleInfo.is_followed"
          ></FollowUser>
          <!-- :value="articleInfo.is_followed"
            @input="articleInfo.is_followed = $event" -->
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content"
          v-html="articleInfo.content"
          ref="content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 评论组件,写在正文结束之后 -->
        <CommentList
          @replyHandler="replyHandler"
          :source-id="articleInfo.art_id"
          @sendTotal="totalCommentCount = $event"
          :list="CommentList"
        >
        </CommentList>

        <!-- 品论弹出层 -->
        <van-popup v-model="isPostShow" position="bottom">
          <CommentPost
            @postSuccess="postSuccess"
            :target-id="articleInfo.art_id"
          >
          </CommentPost>
        </van-popup>

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            @click="isPostShow = true"
            class="comment-btn"
            type="default"
            round
            size="small"
            >写评论</van-button
          >
          <van-icon name="comment-o" :badge="totalCommentCount" color="#777" />
          <!-- <van-icon color="#777" name="star-o" /> -->
          <!-- 收藏组件 -->
          <CollectUser
            v-model="articleInfo.is_collected"
            :articleId="articleInfo.aut_id"
          ></CollectUser>
          <!-- 点赞组件  -->
          <LikeArticle
            :articleId="articleInfo.art_id"
            :attitude="articleInfo.attitude"
            @input="articleInfo.attitude = $event"
          ></LikeArticle>
          <!-- <van-icon color="#777" name="good-job-o" /> -->
          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-if="statusCode === 4">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-if="statusCode === 3">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="initData">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
    <!------------------------ 评论回复 ------------------------------>
    <van-popup v-model="isReplyShow" position="bottom" style="height: 100%">
      <CommentReply
        v-if="isReplyShow"
        :comment-data="currentComment"
        @close="isReplyShow = false"
      ></CommentReply>
    </van-popup>
    <!------------------------ /评论回复 ------------------------------>
  </div>
</template>

<script>
/*
 */
import { getArticleInfoApi } from "@/api/article";
import { ImagePreview } from "vant";
import FollowUser from "@/components/follow-user";
import CollectUser from "@/components/collect-user";
import LikeArticle from "@/components/like-user";
import CommentList from "./components/comment-list";
import CommentPost from "./components/comment-post.vue";
import CommentReply from "./components/comment-reply.vue";
export default {
  name: "ArticleIndex",
  components: {
    FollowUser,
    CollectUser,
    LikeArticle,
    CommentList,
    CommentPost,
    CommentReply,
  },
  props: {},
  data() {
    return {
      articleInfo: {}, //存储请求过来的文章信息
      articleId: this.$route.params.id,
      isLoading: false,
      statusCode: 1, //1表示加载中 2表示加载成功 3表示加载失败 4表示页面不存在
      totalCommentCount: "",
      isPostShow: false, //定义布尔变量控制弹框打开关闭
      CommentList: [],
      isReplyShow: false,
      currentComment: {},
    };
  },
  provide() {
    return {
      articleId: this.articleId,
    };
  },
  computed: {},
  watch: {},
  created() {
    this.initData();
  },
  mounted() {},
  methods: {
    //this.$route--当前页面路由信息
    //this.$route.params--动态路由的数据 -- /article/200
    //this.$route.query -- 查询参数--- /article?id=200
    async initData() {
      //一进去,显示加载中,在加载文章内容
      this.statusCode = 1;
      try {
        let { data } = await getArticleInfoApi(this.articleId);
        console.log(data);
        this.articleInfo = data.data;
        //获取导数据之后,将状态设置为2,则表示加载成功
        this.statusCode = 2;
        //加载成功之后要显示其中的图片,因为渲染数据是耗时任务,所以需要等页面渲染完成之后再获取页面中的img元素
        this.$nextTick(() => {
          //找到文章中的所有的图片标签
          // const imageNodes = this.$refs.content.querySelectorAll("img");
          const imageNodes = document
            .querySelector(".article-content")
            .querySelectorAll("img");
          //将图片标签的地址组合成为一个数组
          //imageNodes本身是一个nodelist,需要用Array.from转化才能使用map方法
          //找出每一项的src值
          const imgSrc = Array.from(imageNodes).map((item) => item.src);
          //给每一个图片绑定点击事件,调用预览函数,传入点击项的索引
          // imageNodes.forEach((img, idx) => {
          //   img.onclick = function () {
          //     ImagePreview({
          //       images: imgSrc,
          //       startPosition: idx,
          //     });
          //   };
          // });
          imageNodes.forEach((item, idx) => {
            item.onclick = function () {
              ImagePreview({
                images: imgSrc,
                startPosition: idx,
              });
            };
          });
        });
      } catch (error) {
        // console.log(error);
        if (error.response && error.response.status === 404) {
          this.statusCode = 4;
        } else {
          this.statusCode = 3;
        }
      }
    },
    // updateFollow(val) {
    //   this.articleInfo.is_followed = val;
    // },
    postSuccess(val) {
      //val时comment-post组件传递过来的新增成功的数据
      //将数据放在comment-list中的list中,等于放在index.vue中的commentlist中
      this.CommentList.unshift(val);
      this.isPostShow = false;
      this.totalCommentCount++;
    },
    replyHandler(val) {
      // console.log(val, "33333333");
      this.isReplyShow = true;
      this.currentComment = val;
    },
  },
};
</script>

<style scoped lang="less">
// @import "@/styles/github-markdown(1).css";
@import "@/styles/github-markdown(1).css";
.article-container {
  .comment-reply {
    /deep/.van-nav-bar {
      background-color: orange;
    }
  }

  /deep/.van-nav-bar__title {
    color: #fff;
  }
  /deep/ .van-icon {
    color: #fff;
  }
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
